﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelSite.Entities;
using Dapper;

namespace TravelSite.DAL.Repositories
{
    public class TourCompanyRepository : BaseRepository<TourCompany>
    {
        protected override string TableName
        {
            get { return "[TourCompanies]"; }
        }

        public override IEnumerable<TourCompany> FindAll()
        {
            string strSQL = @"  select vo.TourCompanyId, vo.TourCompanyName, vo.IsDefault, 
                    convert(bit, case 
                                    when 1 = 0 then 0
                                else 1 end) as CanDelete
                    from [TourCompanies] (nolock) as vo 
                    order by vo.TourCompanyName ";

            IEnumerable<TourCompany> result = Connection.Query<TourCompany>(strSQL);
            return result;
        }

        public override TourCompany Find(int id)
        {
            TourCompany result = Connection.Query<TourCompany>(
                @"  select vo.TourCompanyId, vo.TourCompanyName, vo.IsDefault
                    from [TourCompanies] (nolock) as vo
                    where vo.TourCompanyId = @TourCompanyId", new { TourCompanyId = id }).SingleOrDefault();
            return result;
        }

        public override void Insert(TourCompany item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update TourCompanies set IsDefault = 0");

            Connection.Execute(
                @"insert into [TourCompanies] 
                (TourCompanyName, IsDefault)
                values (@TourCompanyName, @IsDefault)", item);
        }

        public override void Update(TourCompany item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update TourCompanies set IsDefault = 0");

            Connection.Execute(
                @"update TourCompanies
                    set TourCompanyName = @TourCompanyName, IsDefault = @IsDefault
                    where (TourCompanyId = @TourCompanyId)", item);
        }

        public override void Delete(int id)
        {
            Connection.Execute(
                @"delete 
                    from TourCompanies
                    where (TourCompanyId = @TourCompanyId)", new { TourCompanyId = id });
        }

    }
}
